package com.wing.purchase.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.chanjet.entity.product.ProductCreateRequest;
import com.wing.chanjet.entity.product.ProductRdrecordDetailsRequest;
import com.wing.chanjet.entity.supplier.request.SupplierPartnerClassCreateRequest;
import com.wing.chanjet.entity.warehouse.request .PurchaseCreateDtoRequest;
import com.wing.chanjet.entity.warehouse.request.PurchaseCreateRequest;
import com.wing.chanjet.entity.warehouse.request.RdrecordDetailsRequest;
import com.wing.chanjet.feign.ChanjetClient;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.order.model.entity.CabInventoryProduct;
import com.wing.order.model.entity.CabInventoryProductRecord;
import com.wing.order.service.CabInventoryProductRecordService;
import com.wing.order.service.CabInventoryProductService;
import com.wing.platform.order.model.entity.Warehouse;
import com.wing.product.model.entity.ProductPackLabel;
import com.wing.product.service.DynamicService;
import com.wing.product.service.ProductPackLabelService;
import com.wing.purchase.dao.*;
import com.wing.purchase.model.entity.*;
import com.wing.purchase.model.request.PurchaseSignForForm;
import com.wing.purchase.model.request.PurchaseSkuItermForm;
import com.wing.purchase.model.request.PurchaseStorageWorkForm;
import com.wing.purchase.model.request.SimpleStorageForm;
import com.wing.purchase.model.response.*;
import com.wing.purchase.util.PurchaseSignUtil;
import com.wing.storage.dao.PalletBoxSkuItermDao;
import com.wing.storage.dao.WarehouseAreaSkuItermDao;
import com.wing.storage.model.entity.*;
import com.wing.storage.service.PalletBoxSkuItermService;
import com.wing.storage.service.ProductInventoryDetailService;
import com.wing.storage.service.ProductInventoryRecordService;
import com.wing.storage.service.ProductInventoryService;
import com.wing.visual.dao.WarehouseDao;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 采购入库作业-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class PurchaseStorageWorkServiceImpl extends ServiceImpl<PurchaseStorageWorkDao, PurchaseStorageWork> implements PurchaseStorageWorkService {

    @Autowired
    private DynamicService dynamicService;
    @Autowired
    private PurchaseWarehousingPlanService purchaseWarehousingPlanService;
    @Autowired
    private PurchaseSignForService purchaseSignForService;
    @Autowired
    private PurchaseSignForProductService purchaseSignForProductService;
    @Autowired
    private PurchaseStorageWorkProductService purchaseStorageWorkProductService;
    @Autowired
    private CabInventoryProductService cabInventoryProductService;
    @Autowired
    private CabInventoryProductRecordService cabInventoryProductRecordService;
    @Autowired
    private PalletBoxListDao palletBoxListDao;
    @Autowired
    private BoxLabelDao boxLabelDao;
    @Autowired
    private ProductPackLabelService productPackLabelService;
    @Autowired
    private WarehouseShelfSpaceLabelDao warehouseShelfSpaceLabelDao;

    @Autowired
    private ProductInventoryDetailService productInventoryDetailService;

    @Autowired
    private ChanjetClient chanjetClient;

    @Autowired
    private WarehouseAreaSkuItermDao warehouseAreaSkuItermDao;

    @Autowired
    private PalletBoxSkuItermDao palletBoxSkuItermDao;

    @Autowired
    private WarehouseDao warehouseDao;

    @Autowired
    private PalletBoxSkuItermService palletBoxSkuItermService;

    @Autowired
    WarehouseShelfSpaceDao warehouseShelfSpaceDao;

    @Autowired
    PurchaseSignForDao purchaseSignForDao;


    @Override
/*    @Transactional(readOnly = false)*/
    public int add(PurchaseStorageWorkForm purchaseStorageWorkForm) {

        BigDecimal quantity = purchaseStorageWorkForm.getPurchaseStorageWorkProduct().getQuantity();
        if(quantity==null){
            throw new BusinessException(300, "入库数量为空！");
        }
        if (quantity != null && quantity.compareTo(BigDecimal.ZERO) == 0) {
            throw new BusinessException(300, "待入库数量不足，请重新填写！");
        }
        if (quantity != null && quantity.compareTo(BigDecimal.ZERO) < 0) {
            throw new BusinessException(300, "待入库数量不足，请重新填写！");
        }
        if(StringUtils.isEmpty(purchaseStorageWorkForm.getSkuCode())){
            throw new BusinessException(300, "物料编码为空！");
        }
        if(StringUtils.isEmpty(purchaseStorageWorkForm.getSkuName())){
            throw new BusinessException(300, "物料名称为空！");
        }

        PurchaseSignFor purchaseSignFor = purchaseSignForDao.selectById(purchaseStorageWorkForm.getPurchaseSignForId());
        if(purchaseSignFor==null){
            throw new BusinessException(300, "签收单不存在!");
        }

        if(purchaseStorageWorkForm.getPurchaseSignForId()==null){
            throw new BusinessException(300, "采购入库签收ID不能为空!");
        }


        if(purchaseStorageWorkForm.getPurchaseStorageWorkProduct().getProductDetailId()==null || purchaseStorageWorkForm.getPurchaseStorageWorkProduct().getProductDetailId()==0){
            throw new BusinessException(300, "签收入库物料id为空!");
        }
        if(purchaseStorageWorkForm.getPurchaseStorageWorkProduct().getWarehouseId()==null){
            throw new BusinessException(300, "仓库为空!");
        }
        if(purchaseStorageWorkForm.getPurchaseStorageWorkProduct().getWarehouseAreaId()==null){
            throw new BusinessException(300, "仓库库区为空!");
        }
        if(purchaseStorageWorkForm.getPurchaseStorageWorkProduct().getWarehouseShelfSpaceId()==null){
            throw new BusinessException(300, "仓库库位为空!");
        }

        // 当前采购入库作业签收数量
        BigDecimal curSignNum = BigDecimal.ZERO;
        if (purchaseStorageWorkForm.getPurchaseStorageWorkProduct() == null) {
            throw new BusinessException(300, "入库作业产品不能为空!");
        }
        //采购签收产品ID
        Long purchaseSignForProductId = purchaseStorageWorkForm.getPurchaseStorageWorkProduct().getPurchaseSignForProductId();
        if (purchaseSignForProductId == null) {
            throw new BusinessException(300, "参数错误,采购签收产品ID不能为空");
        }


        // 获取当前入库产品剩余入库数
        BigDecimal surplusStorageNum = baseMapper.getSurplusStorageNum(purchaseSignForProductId);
        // 获取签收数
        curSignNum = curSignNum.add(purchaseStorageWorkForm.getPurchaseStorageWorkProduct().getQuantity());
        // 校验签收数是否大于剩余入库数
        if (curSignNum.compareTo(surplusStorageNum) > 0) {
            throw new BusinessException(300, "签收数不能大于待入库数量！");
        }

        purchaseStorageWorkForm.setExternalCode(getCjtNumber());

        //校验
        PurchaseStorageWork purchaseStorageWork = new PurchaseStorageWork();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(PurchaseStorageWork.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(purchaseStorageWorkForm, purchaseStorageWork, copyOptions);
        purchaseStorageWork.setSubUnitCode(purchaseStorageWorkForm.getUnitCode());
        purchaseStorageWork.setSubUnitId(purchaseStorageWorkForm.getUnitId());

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String code = dynamicService.getMaxCode("work_no", "pur_purchase_storage_work");
        String day = simpleDateFormat.format(new Date());
        purchaseStorageWork.setWorkNo("PW" + day + code);
        int i = baseMapper.insert(purchaseStorageWork);
        if (i > 0) {
            //新增采购入库产品作业记录2 product_inventory_id
            PurchaseStorageWorkProduct purchaseStorageWorkProduct = purchaseStorageWorkForm.getPurchaseStorageWorkProduct();
            purchaseStorageWorkProduct.setPurchaseStorageWorkId(purchaseStorageWork.getId());
            purchaseStorageWorkProduct.setCreateTime(LocalDateTime.now());
            purchaseStorageWorkProductService.save(purchaseStorageWorkProduct);
            //产品库存-入库
            ProductInventoryDetail productInventoryDetail = new ProductInventoryDetail();
            productInventoryDetail.setInoutType(purchaseStorageWorkProduct.getWarehouseInventoryTypeId());
            productInventoryDetail.setInoutWorkJob(purchaseStorageWork.getId());
            productInventoryDetail.setProductDetailId(purchaseStorageWorkProduct.getProductDetailId());
            productInventoryDetail.setWarehouseTypeId(purchaseStorageWorkProduct.getWarehouseTypeId());
            productInventoryDetail.setWarehouseId(purchaseStorageWorkProduct.getWarehouseId());
            productInventoryDetail.setWarehouseAreaId(purchaseStorageWorkProduct.getWarehouseAreaId());

            productInventoryDetail.setWarehouseShelfSpaceId(purchaseStorageWorkProduct.getWarehouseShelfSpaceId());
            productInventoryDetail.setPalletBoxId(purchaseStorageWorkProduct.getPalletBoxId());
           // productInventoryDetail.setQuantity(purchaseStorageWorkProduct.getQuantity());
            productInventoryDetail.setQuantity(purchaseStorageWorkForm.getQuantity());
            //purchaseStorageWorkForm.getPurchaseStorageWorkProduct().getQuantity()

            WarehouseShelfSpace warehouseShelfSpace = warehouseShelfSpaceDao.selectById(productInventoryDetail.getWarehouseShelfSpaceId());
            if(warehouseShelfSpace!=null){
                productInventoryDetail.setWarehouseShelfId(warehouseShelfSpace.getShelfId());
            }

            try {
                PurchaseSkuItermForm purchaseSkuItermForm = new PurchaseSkuItermForm();
                purchaseSkuItermForm.setSkuCode(purchaseStorageWorkForm.getSkuCode());
                purchaseSkuItermForm.setSkuName(purchaseStorageWorkForm.getSkuName());
                purchaseSkuItermForm.setWarehouseAreaId(purchaseStorageWorkForm.getPurchaseStorageWorkProduct().getWarehouseAreaId());
                purchaseSkuItermForm.setWarehouseId(purchaseStorageWorkForm.getPurchaseStorageWorkProduct().getWarehouseId());
                purchaseSkuItermForm.setWarehouseShelfSpaceId(purchaseStorageWorkForm.getPurchaseStorageWorkProduct().getWarehouseShelfSpaceId());
                purchaseSkuItermForm.setPalletBoxId(purchaseStorageWorkForm.getPurchaseStorageWorkProduct().getPalletBoxId());
                purchaseSkuItermForm.setNum(purchaseStorageWorkForm.getQuantity());
                purchaseSkuItermForm.setWarehouseShelfId(productInventoryDetail.getWarehouseShelfId());
                savePurchasePalletBoxAndAreaSkuIterm(purchaseSkuItermForm);

            }catch (Exception e){
                log.info("保存料箱存货明细出现错误："+e);
            }

            productInventoryDetailService.productInStorage(productInventoryDetail);

            //todo 更改签收记录为 已签收已完成
            toChangeStatus(purchaseStorageWorkForm.getInventoryTypeCode(),purchaseStorageWorkForm.getPurchaseSignForId());


            if(purchaseStorageWorkForm.getInTypeName()!=null && purchaseStorageWorkForm.getInTypeName().equals("采购入库")){
                productPurchaseInStorage(purchaseStorageWorkForm);
            }else if(purchaseStorageWorkForm.getInTypeName()!=null && purchaseStorageWorkForm.getInTypeName().equals("生产成品入库")){
                productFinishInStorage(purchaseStorageWorkForm);
            }


        }

        return i;
    }



    @Override
    public List<PurchaseStorageWorkVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<PurchaseStorageWorkVO> pageList4app(Page page, Map<String, Object> params) {
        List<PurchaseStorageWorkVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public PurchaseStorageWorkVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public int simpleStorage(SimpleStorageForm simpleStorageForm) {

        if (simpleStorageForm.getQuantity() == null) {
            throw new BusinessException(300, "错误：入库数量不能为 null");
        }

        if (simpleStorageForm.getQuantity().compareTo(BigDecimal.ZERO) <= 0) {
            throw new BusinessException(300,"错误：入库数量必须大于0。您输入的数量是 " + simpleStorageForm.getQuantity());
        }

        PurchaseStorageWork purchaseStorageWork = new PurchaseStorageWork();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String code = dynamicService.getMaxCode("work_no", "pur_purchase_storage_work");
        String day = simpleDateFormat.format(new Date());
        purchaseStorageWork.setWorkNo("PW" + day + code);
        int i = baseMapper.insert(purchaseStorageWork);
        if (i > 0) {
            //新增采购入库产品作业记录
            PurchaseStorageWorkProduct purchaseStorageWorkProduct = new PurchaseStorageWorkProduct();
            purchaseStorageWorkProduct.setPurchaseStorageWorkId(purchaseStorageWork.getId());
            purchaseStorageWorkProduct.setProductTypeId(simpleStorageForm.getProductTypeId());
            purchaseStorageWorkProduct.setProductDetailId(simpleStorageForm.getProductDetailId());
            purchaseStorageWorkProduct.setQuantity(simpleStorageForm.getQuantity());
            if(StringUtils.isNotBlank(simpleStorageForm.getInType())){
                purchaseStorageWorkProduct.setWarehouseInventoryTypeId(Long.valueOf(simpleStorageForm.getInType()));
            }
            purchaseStorageWorkProduct.setWarehouseTypeId(simpleStorageForm.getWarehouseTypeId());
            purchaseStorageWorkProduct.setWarehouseId(simpleStorageForm.getWarehouseId());
            purchaseStorageWorkProduct.setWarehouseAreaId(simpleStorageForm.getWarehouseAreaId());
            purchaseStorageWorkProduct.setWarehouseShelfId(simpleStorageForm.getWarehouseShelfId());
            purchaseStorageWorkProduct.setWarehouseShelfSpaceId(simpleStorageForm.getWarehouseShelfSpaceId());
            purchaseStorageWorkProduct.setPalletBoxId(simpleStorageForm.getPalletBoxId());
            purchaseStorageWorkProduct.setCreateTime(LocalDateTime.now());
            purchaseStorageWorkProduct.setCreator(JwtUtils.getLoginUserId());
            purchaseStorageWorkProduct.setPrice(simpleStorageForm.getPrice());
            purchaseStorageWorkProduct.setTotalPrice(simpleStorageForm.getTotalPrice());
            purchaseStorageWorkProduct.setCreatorName(JwtUtils.getLoginUsername());
            purchaseStorageWorkProduct.setBatchNumber(simpleStorageForm.getBatchNumber());
            purchaseStorageWorkProduct.setInDanPrice(simpleStorageForm.getInDanPrice());
            purchaseStorageWorkProductService.save(purchaseStorageWorkProduct);
            //产品库存-入库2
            ProductInventoryDetail productInventoryDetail = new ProductInventoryDetail();
            if(StringUtils.isNotBlank(simpleStorageForm.getInType())){
                productInventoryDetail.setInoutType(Long.valueOf(simpleStorageForm.getInType()));
            }
            productInventoryDetail.setInoutWorkJob(purchaseStorageWork.getId());
            productInventoryDetail.setProductDetailId(simpleStorageForm.getProductDetailId());
            productInventoryDetail.setWarehouseTypeId(purchaseStorageWorkProduct.getWarehouseTypeId());
            productInventoryDetail.setWarehouseId(purchaseStorageWorkProduct.getWarehouseId());
            productInventoryDetail.setWarehouseAreaId(purchaseStorageWorkProduct.getWarehouseAreaId());
/*
            productInventoryDetail.setWarehouseShelfId(purchaseStorageWorkProduct.getWarehouseShelfId());
*/
            productInventoryDetail.setWarehouseShelfSpaceId(purchaseStorageWorkProduct.getWarehouseShelfSpaceId());
            productInventoryDetail.setPalletBoxId(purchaseStorageWorkProduct.getPalletBoxId());
            productInventoryDetail.setQuantity(purchaseStorageWorkProduct.getQuantity());

            WarehouseShelfSpace warehouseShelfSpace = warehouseShelfSpaceDao.selectById(purchaseStorageWorkProduct.getWarehouseShelfSpaceId());
            if(warehouseShelfSpace!=null){
                productInventoryDetail.setWarehouseShelfId(warehouseShelfSpace.getShelfId());
            }

            productInventoryDetailService.productInStorage(productInventoryDetail);

            PurchaseSkuItermForm purchaseSkuItermForm = new PurchaseSkuItermForm();
            purchaseSkuItermForm.setSkuCode(simpleStorageForm.getSkuCode());
            purchaseSkuItermForm.setSkuName(simpleStorageForm.getSkuName());
            purchaseSkuItermForm.setWarehouseAreaId(simpleStorageForm.getWarehouseAreaId());
            purchaseSkuItermForm.setWarehouseId(simpleStorageForm.getWarehouseId());
            purchaseSkuItermForm.setWarehouseShelfSpaceId(simpleStorageForm.getWarehouseShelfSpaceId());
            purchaseSkuItermForm.setPalletBoxId(simpleStorageForm.getPalletBoxId());
            purchaseSkuItermForm.setNum(simpleStorageForm.getQuantity());
            purchaseSkuItermForm.setWarehouseShelfId(productInventoryDetail.getWarehouseShelfId());

            savePurchasePalletBoxAndAreaSkuIterm(purchaseSkuItermForm);
        }
         return i;
    }

    @Override
    public Page<PurchaseProductInfoVO> getInProductInfoDetail(Page page, Map<String, Object> params) {
        List<PurchaseProductInfoVO> list = baseMapper.getInProductInfoDetail(page, params);
        page.setRecords(list);
        return page;
     }

    @Override
    public Page<PurchaseProductInfoVO> getInProductInfoDetailStatic(Page page, Map<String, Object> params) {
        List<PurchaseProductInfoVO> list = baseMapper.getInProductInfoDetailStatic(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public List<PurchaseDetailStaticExportVO> toInProductInfoDetailStaticExport(Map<String, Object> params) {
        return baseMapper.toInProductInfoDetailStaticExport(params);
    }

    @Override
    public List<PurchaseDetailExportVO> exportInProductInfoDetail(Map<String, Object> params) {
        return baseMapper.exportInProductInfoDetail(params);
    }

    @Override
    public List<PurchaseStorageWorkExportVO> exportInWorkList4app(Page page, Map<String, Object> params) {

        List<PurchaseStorageWorkExportVO> bigList = new ArrayList<>();
        List<PurchaseStorageWorkVO> list = baseMapper.list4app(page, params);
        for (PurchaseStorageWorkVO purchaseStorageWorkVO : list) {
            PurchaseStorageWorkExportVO purchaseSignForExportVO=new PurchaseStorageWorkExportVO();
            BeanUtils.copyProperties(purchaseStorageWorkVO, purchaseSignForExportVO);
            bigList.add(purchaseSignForExportVO);
        }

        return bigList;
    }

    /**
     * 采购入库
     * @param purchaseStorageWorkForm
     */
    public void productPurchaseInStorage(PurchaseStorageWorkForm purchaseStorageWorkForm){


        //新增采购入库单到畅捷通平台
        try {

            SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
            String workDate = simpleDateFormat2.format(new Date());

            PurchaseCreateRequest purchaseCreateRequest=new PurchaseCreateRequest();

            purchaseCreateRequest.setExternalCode(purchaseStorageWorkForm.getExternalCode());
            purchaseCreateRequest.setVoucherDate(workDate);

            PurchaseCreateRequest.PurchaseVoucherTypeRequest purchaseVoucherTypeRequest=purchaseCreateRequest.new PurchaseVoucherTypeRequest();
            purchaseVoucherTypeRequest.setCode("ST1001");
            purchaseCreateRequest.setVoucherType(purchaseVoucherTypeRequest);

            PurchaseCreateRequest.PurchaseBusiTypeRequest purchaseBusiTypeRequest=purchaseCreateRequest.new PurchaseBusiTypeRequest();
            purchaseBusiTypeRequest.setCode("01");
            purchaseCreateRequest.setBusiType(purchaseBusiTypeRequest);


            //仓库信息
            PurchaseCreateRequest.WarehouseRequest warehouseRequest= purchaseCreateRequest.new WarehouseRequest();
            String warehouseId = purchaseStorageWorkForm.getWarehouseId();
            if(warehouseId!=null){
                Warehouse warehouse = warehouseDao.selectById(warehouseId);
                if(warehouse!=null){
                    warehouseRequest.setCode(warehouse.getCode());
                    warehouseRequest.setName(warehouse.getName());
                }
            }
            purchaseCreateRequest.setWarehouse(warehouseRequest);

            PurchaseStorageWorkProduct purchaseStorageWorkProduct = purchaseStorageWorkForm.getPurchaseStorageWorkProduct();


            //往来单位信息
            PurchaseCreateRequest.PurchasePartnerRequest purchasePartnerRequest=purchaseCreateRequest.new PurchasePartnerRequest();
            purchasePartnerRequest.setCode(purchaseStorageWorkProduct.getSupplierCode());
            purchasePartnerRequest.setName(purchaseStorageWorkProduct.getSupplierName());
            purchaseCreateRequest.setPartner(purchasePartnerRequest);

            List<RdrecordDetailsRequest> rdrecordDetailsRequestList=new ArrayList<>();


            RdrecordDetailsRequest rdrecordDetailsRequest= new RdrecordDetailsRequest();
            rdrecordDetailsRequest.setQuantity(purchaseStorageWorkForm.getPurchaseStorageWorkProduct().getQuantity());

             RdrecordDetailsRequest.InventoryRequest inventoryRequest=rdrecordDetailsRequest.new InventoryRequest();
            inventoryRequest.setCode(purchaseStorageWorkForm.getSkuCode());
            inventoryRequest.setName(purchaseStorageWorkForm.getSkuName());
            rdrecordDetailsRequest.setInventory(inventoryRequest);

             RdrecordDetailsRequest.UnitRequest unitRequest=rdrecordDetailsRequest.new UnitRequest();
            unitRequest.setCode(purchaseStorageWorkForm.getUnitCode());
            unitRequest.setName(purchaseStorageWorkForm.getSubUnitName());
            rdrecordDetailsRequest.setUnit(unitRequest);
            rdrecordDetailsRequestList.add(rdrecordDetailsRequest);

            purchaseCreateRequest.setRDRecordDetails(rdrecordDetailsRequestList);
            purchaseCreateRequest.setRes(rdrecordDetailsRequestList);

            PurchaseCreateDtoRequest purchaseCreateDtoRequest=new PurchaseCreateDtoRequest();
            purchaseCreateDtoRequest.setDto(purchaseCreateRequest);
            JsonResult jsonResult = chanjetClient.syncAddPurchaseWork(purchaseCreateDtoRequest);
            System.out.println(jsonResult+"-----"+purchaseCreateDtoRequest);


        }catch (Exception e){
          /*  e.printStackTrace();*/
            log.info("采购入库失败-畅捷通:",e);
        }

    }

    public String getCjtNumber(){
        // 获取当前日期和时间
        LocalDateTime now = LocalDateTime.now();

        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

        // 格式化当前日期和时间
        String formattedDateTime = now.format(formatter);

        // 生成最终字符串
        String result = "PECJT" + formattedDateTime;

        return result;
    }


    /**
     * 保存 库位存货明细和料箱存货明细
     * @param purchaseSkuItermForm
     */
    public void savePurchasePalletBoxAndAreaSkuIterm(PurchaseSkuItermForm purchaseSkuItermForm){
        //查看当前仓库  是否料箱库？
        Warehouse warehouse = warehouseDao.selectById(purchaseSkuItermForm.getWarehouseId());
        try {
            if(warehouse!=null){
                // 0 是 1 否
                if(warehouse.getWorkbinStatus()!=null){
                    if(warehouse.getWorkbinStatus()==1L){
                        //库位存货明细
                        saveWarehouseAreaSkuIterm(purchaseSkuItermForm);
                    }else{
                        PalletBoxSkuIterm palletBoxSkuIterm=new PalletBoxSkuIterm();
                        palletBoxSkuIterm.setSkuName(purchaseSkuItermForm.getSkuName());
                        palletBoxSkuIterm.setSkuCode(purchaseSkuItermForm.getSkuCode());
                        palletBoxSkuIterm.setWarehouseShelfSpaceId(purchaseSkuItermForm.getWarehouseShelfSpaceId());
                        palletBoxSkuIterm.setWarehouseId(purchaseSkuItermForm.getWarehouseId());
                        palletBoxSkuIterm.setWarehouseAreaId(purchaseSkuItermForm.getWarehouseAreaId());
                        palletBoxSkuIterm.setNum(purchaseSkuItermForm.getNum());
                        palletBoxSkuIterm.setPalletBoxId(purchaseSkuItermForm.getPalletBoxId());



                        palletBoxSkuIterm.setWarehouseShelfId(purchaseSkuItermForm.getWarehouseShelfId());

                        QueryWrapper<PalletBoxSkuIterm> detailQueryWrapper = new QueryWrapper<>();
                        detailQueryWrapper.eq("sku_code", purchaseSkuItermForm.getSkuCode());
                        detailQueryWrapper.eq("warehouse_id", purchaseSkuItermForm.getWarehouseId());
                        detailQueryWrapper.eq("warehouse_area_id", purchaseSkuItermForm.getWarehouseAreaId());
                        detailQueryWrapper.eq("warehouse_shelf_space_id", purchaseSkuItermForm.getWarehouseShelfSpaceId());
                        detailQueryWrapper.eq("pallet_box_id", purchaseSkuItermForm.getPalletBoxId()==null?0L:purchaseSkuItermForm.getPalletBoxId());

                        PalletBoxSkuIterm palletBoxSkuIterm2 = palletBoxSkuItermDao.selectOne(detailQueryWrapper);
                        BigDecimal kcNum = BigDecimal.ZERO;
                        if(palletBoxSkuIterm2!=null){
                            kcNum = palletBoxSkuIterm2.getNum().add(purchaseSkuItermForm.getNum());
                            palletBoxSkuIterm2.setNum(kcNum);
                            palletBoxSkuIterm2.setUpdateTime(LocalDateTime.now());
                            palletBoxSkuItermService.updateById(palletBoxSkuIterm2);
                        }else{
                            palletBoxSkuItermService.save(palletBoxSkuIterm);
                        }

                        //库位存货明细
                        saveWarehouseAreaSkuIterm(purchaseSkuItermForm);
                    }
                }else{
                     //库位存货明细
                    saveWarehouseAreaSkuIterm(purchaseSkuItermForm);

                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }


    }



    /**
     * 保存库位存货明细
     * @param purchaseStorageWorkForm
     */
    public void saveWarehouseAreaSkuIterm(PurchaseSkuItermForm  purchaseStorageWorkForm) {
        WarehouseAreaSkuIterm warehouseAreaSkuIterm=new WarehouseAreaSkuIterm();
        warehouseAreaSkuIterm.setSkuName(purchaseStorageWorkForm.getSkuName());
        warehouseAreaSkuIterm.setSkuCode(purchaseStorageWorkForm.getSkuCode());
        warehouseAreaSkuIterm.setWarehouseShelfSpaceId(purchaseStorageWorkForm.getWarehouseShelfSpaceId());
        warehouseAreaSkuIterm.setWarehouseId(purchaseStorageWorkForm.getWarehouseId());
        warehouseAreaSkuIterm.setWarehouseAreaId(purchaseStorageWorkForm.getWarehouseAreaId());
        warehouseAreaSkuIterm.setNum(purchaseStorageWorkForm.getNum());
        warehouseAreaSkuIterm.setWarehouseShelfId(purchaseStorageWorkForm.getWarehouseShelfId());


        QueryWrapper<WarehouseAreaSkuIterm> detailQueryWrapper = new QueryWrapper<>();
        detailQueryWrapper.eq("sku_code", purchaseStorageWorkForm.getSkuCode());
        detailQueryWrapper.eq("warehouse_id", purchaseStorageWorkForm.getWarehouseId());
        detailQueryWrapper.eq("warehouse_area_id", purchaseStorageWorkForm.getWarehouseAreaId());
        detailQueryWrapper.eq("warehouse_shelf_space_id", purchaseStorageWorkForm.getWarehouseShelfSpaceId());
        WarehouseAreaSkuIterm warehouseAreaSkuIterm1 = warehouseAreaSkuItermDao.selectOne(detailQueryWrapper);
        BigDecimal kcNum = BigDecimal.ZERO;
        if(warehouseAreaSkuIterm1!=null){
            kcNum = warehouseAreaSkuIterm1.getNum().add(purchaseStorageWorkForm.getNum());
            warehouseAreaSkuIterm1.setNum(kcNum);
            warehouseAreaSkuIterm1.setUpdateTime(LocalDateTime.now());
            warehouseAreaSkuItermDao.updateById(warehouseAreaSkuIterm1);
        }else{
            warehouseAreaSkuItermDao.insert(warehouseAreaSkuIterm);
        }
    }


    /**
     * 产成品入库
     * @param purchaseStorageWorkForm
     */
    public void productFinishInStorage(PurchaseStorageWorkForm purchaseStorageWorkForm){


        //新增采购入库单到畅捷通平台
        try {

            SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
            String workDate = simpleDateFormat2.format(new Date());

            ProductCreateRequest purchaseCreateRequest=new ProductCreateRequest();

            purchaseCreateRequest.setExternalCode(purchaseStorageWorkForm.getExternalCode());
            purchaseCreateRequest.setVoucherDate(workDate);


            ProductCreateRequest.PurchaseBusiTypeRequest purchaseBusiTypeRequest=purchaseCreateRequest.new PurchaseBusiTypeRequest();
            purchaseBusiTypeRequest.setCode("03");
            purchaseCreateRequest.setBusiType(purchaseBusiTypeRequest);


            //仓库信息
            ProductCreateRequest.WarehouseRequest warehouseRequest= purchaseCreateRequest.new WarehouseRequest();
            String warehouseId = purchaseStorageWorkForm.getWarehouseId();
            if(warehouseId!=null){
                Warehouse warehouse = warehouseDao.selectById(warehouseId);
                if(warehouse!=null){
                    warehouseRequest.setCode(warehouse.getCode());
                    warehouseRequest.setName(warehouse.getName());
                }
            }
            purchaseCreateRequest.setWarehouse(warehouseRequest);



            List<ProductRdrecordDetailsRequest> rdrecordDetailsRequestList=new ArrayList<>();


            ProductRdrecordDetailsRequest rdrecordDetailsRequest= new ProductRdrecordDetailsRequest();
            rdrecordDetailsRequest.setBaseQuantity(purchaseStorageWorkForm.getPurchaseStorageWorkProduct().getQuantity());

            ProductRdrecordDetailsRequest.InventoryRequest inventoryRequest=rdrecordDetailsRequest.new InventoryRequest();
            inventoryRequest.setCode(purchaseStorageWorkForm.getSkuCode());
             rdrecordDetailsRequest.setInventory(inventoryRequest);

            rdrecordDetailsRequestList.add(rdrecordDetailsRequest);

            purchaseCreateRequest.setRDRecordDetails(rdrecordDetailsRequestList);
            purchaseCreateRequest.setRes(rdrecordDetailsRequestList);
            purchaseCreateRequest.setMemo("产成品系统入库！");
            JsonResult jsonResult = chanjetClient.syncInProductReceive(purchaseCreateRequest);
            System.out.println(jsonResult+"-----"+jsonResult);

        }catch (Exception e){
            /*  e.printStackTrace();*/
            log.info("产成品入库失败-畅捷通:",e);
            e.printStackTrace();
        }

    }

    @Autowired
    private PurchaseDeliveryRecordProductDao purchaseDeliveryRecordProductDao;



    /**
     * 已签收数==发货数量的时候 修改状态为已签收已完成
     * @param
     */
    public void toChangeStatus(String inventoryTypeCode,Long purchaseSignForId){
        try {
            Boolean flag=true;
            //通过签收ID 获取采购发货记录id
            Long purchaseDeliveryRecordIdBySignForId = purchaseDeliveryRecordProductDao.getPurchaseDeliveryRecordIdBySignForId(purchaseSignForId);
            if(purchaseDeliveryRecordIdBySignForId!=null){
                //签收类型
                if(PurchaseSignUtil.CGR.equals(inventoryTypeCode)){
                    //采购入库
                    List<PurchaseDeliveryRecordProductVO> purchaseDeliveryRecordProduct = purchaseDeliveryRecordProductDao.getPurchaseDeliveryRecordProduct(purchaseDeliveryRecordIdBySignForId);



                    //进行校验  签收数量是否大于 采购数量
                    if(purchaseDeliveryRecordProduct.size()>0){
                        for (PurchaseDeliveryRecordProductVO purchaseDeliveryRecordProductVO : purchaseDeliveryRecordProduct) {
                            //发货数量-签收数  =剩余签收数
                            // 剩余签收数量 >= 当前签收数  就可以签收
                            if(purchaseDeliveryRecordProductVO.getQuantity().compareTo(purchaseDeliveryRecordProductVO.getHasSignQuantity()) != 0) {
                                // 当两个BigDecimal值不相等时，执行这里的代码
                                flag=false;
                            }
                        }
                   }

                    //如果都为true 判断总数是否相等，签收数量和入库数量
                    if(flag){
                       BigDecimal signForNum = baseMapper.getSignForNum(purchaseSignForId);
                       BigDecimal totalHasSignQuantity = purchaseDeliveryRecordProduct.stream()
                                .map(PurchaseDeliveryRecordProductVO::getHasSignQuantity) // 获取每个 PurchaseDeliveryRecordProductVO 对象的 hasSignQuantity 字段
                                .reduce(BigDecimal.ZERO, BigDecimal::add); // 使用 reduce 方法进行求和，初始值为 BigDecimal.ZERO
                        // 比较两个 BigDecimal 值是否相等
                        if (signForNum.compareTo(totalHasSignQuantity) == 0) {
                            flag=true;
                        } else {
                            flag=false;
                        }
                  }


                }else if(PurchaseSignUtil.SCR.equals(inventoryTypeCode)){
                    //生产入库
                    List<ProductionTheWorkOrderVO> productionInfo = purchaseSignForDao.getProductionInfo(purchaseDeliveryRecordIdBySignForId);
                    for (ProductionTheWorkOrderVO productionTheWorkOrderVO : productionInfo) {
                        if(productionTheWorkOrderVO.getWorkQuantity()!=productionTheWorkOrderVO.getSignedNum()){
                            flag=false;
                        }
                    }



                }

                if(flag){
                    PurchaseSignFor purchaseSignFor = new PurchaseSignFor();
                    purchaseSignFor.setId(purchaseSignForId);
                    //已签收已完成
                    purchaseSignFor.setStatus("3");
                    // 当两个BigDecimal值相等时，执行这里的代码
                    purchaseSignForDao.updateById(purchaseSignFor);
                }
            }
        }catch (Exception e){
             log.info("变更签收记录状态失败",e);
             e.printStackTrace();
        }



    }


}
